<template>
  <div class="app-container flex flex-sub"
    style="background: none; height: 100%; padding: 1rem">
    <el-card shadow="never"
      class="box-card flex-sub"
      style="overflow: auto">
      <div class="div-query">
        <div class="collapse">
          <div class="collapse-header"
            @click="panelActive = !panelActive">
            <i class="collapse-header-icon"
              :class="[
                panelActive ? 'el-icon-caret-bottom' : 'el-icon-caret-top',
              ]" />
            {{ panelActive ? '隐藏' : '展开' }}查询条件
          </div>
          <div class="collapse-content">
            <el-collapse-transition>
              <div v-show="panelActive">
                <el-form size="small"
                  label-position="right">
                  <el-row>
                    <el-col :span="8">
                      <el-form-item label="网关名称"
                        label-width="80px">
                        <el-input v-model="form.serverName"
                          placeholder="请输入网关名称"
                          clearable
                          class="filter-item search-item"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="网关型号"
                        label-width="80px">
                        <el-input v-model="form.serverModel"
                          placeholder="请输入网关型号"
                          clearable
                          class="filter-item search-item">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="创建时间"
                        label-width="80px">
                        <el-date-picker v-model="form.createdTime"
                          type="datetimerange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          value-format="yyyy-MM-dd HH:mm:ss">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="20">
                      <el-form-item style="text-align: center">
                        <el-button type="primary"
                          icon="el-icon-search"
                          @click="search"
                          style="margin-right: 10px">搜索</el-button>
                        <el-button type="info"
                          icon="el-icon-delete"
                          @click="reset">重置</el-button>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-collapse-transition>
          </div>
        </div>
      </div>
      <div style="margin-bottom: 8px">
        <el-button size="small"
          type="primary"
          style="margin-right: 10px"
          @click="add">
          <i class="iconfont icon-xinzenghuizong"
            style="font-size: 13px;margin-right: 5px" />添加
        </el-button>

        <el-button slot="reference"
          size="small"
          type="danger"
          icon="el-icon-delete"
          @click="multiDelete">
          批量删除
        </el-button>
      </div>

      <el-table size="medium "
        :data="dataList"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
        border
        fit
        :default-sort="{ prop: 'createdTime', order: 'descending' }"
        :header-cell-style="{ background: '#fafafa' }">
        <el-table-column type="selection"> </el-table-column>
        <el-table-column prop="serverName"
          align="center"
          label="网关名称">
        </el-table-column>
        <el-table-column prop="serverModel"
          align="center"
          label="网关型号">
        </el-table-column>
        <el-table-column prop="serverLocation"
          align="center"
          label="所在位置">
        </el-table-column>
        <el-table-column prop="createdTime"
          align="center"
          label="创建时间">
        </el-table-column>
        <el-table-column align="center"
          label="操作"
          width="120">
          <template slot-scope="{ row }">
            <el-tooltip effect="dark"
              content="详情"
              placement="top-start">
              <i class="iconfont icon-chakanxiangqing2 i-detail"
                @click="detail(row)" />
            </el-tooltip>
            <i class="iconfont icon-fengefu i-fengefu" />

            <el-tooltip effect="dark"
              content="编辑"
              placement="top-start">
              <i class="iconfont icon-bianji2 i-edit"
                @click="edit(row)" />
            </el-tooltip>
            <i class="iconfont icon-fengefu i-fengefu" />

            <el-tooltip effect="dark"
              content="删除"
              placement="top-start">
              <i class="iconfont icon-shanchu i-delete"
                @click="handleDelete(row)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0"
        :total="total"
        :page.sync="pagination.pageNum"
        :limit.sync="pagination.pageSize"
        :page-sizes="pageSizeOptions"
        @pagination="getDataList" />
    </el-card>
    <el-dialog :title="title"
      :visible.sync="showDialog"
      top="80px"
      width="50%"
      :before-close="clickCloseBtn"
      :close-on-click-modal="false">
      <div v-if="!isDetail">
        <el-container>
          <el-main :style="{ 'max-height': maxHeightDialog }"
            class="container-main">
            <div class="title">
              <span>填写信息</span>
            </div>
            <el-card class="card"
              shadow="never"
              style="background: #fafafa; min-height: 500px">
              <el-form size="small"
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                label-position="right">
                <div>
                  <el-form-item label="所属部门"
                    prop="deptGuid">
                    <treeselect v-model="ruleForm.deptGuid"
                      :options="deptTree"
                      :normalizer="normalizer"
                      placeholder="请选择所属部门"
                      @select="getDeptNode"
                      :default-expand-level="Infinity" />
                  </el-form-item>
                  <el-form-item label="所属网格"
                    prop="gridMount">
                    <treeselect v-model="ruleForm.gridMount"
                      :options="gridTree"
                      placeholder="请选择所属网格"
                      @select="getGridNode"
                      :default-expand-level="Infinity">
                      <div slot="value-label"
                        slot-scope="{ node }">
                        {{ node.raw.fullPathText }}
                      </div>
                    </treeselect>
                  </el-form-item>
                  <el-form-item label="网关名称:"
                    prop="serverName">
                    <el-input v-model="ruleForm.serverName"
                      placeholder="请输入网关名称"
                      clearable></el-input></el-form-item>
                  <el-form-item label="网关型号"
                    prop="serverModel">
                    <el-input v-model="ruleForm.serverModel"
                      placeholder="请输入网关型号"
                      clearable></el-input></el-form-item>
                  <el-form-item label="所在位置"
                    prop="serverLocation">
                    <el-input v-model="ruleForm.serverLocation"
                      placeholder="请输入所在位置"
                      clearable></el-input></el-form-item>
                  <el-form-item label="维保单位">
                    <el-input v-model="ruleForm.maintenanceUnit"
                      placeholder="请输入维保单位"
                      clearable></el-input></el-form-item>
                  <el-form-item label="维保电话">
                    <el-input v-model="ruleForm.maintenancePhone"
                      placeholder="请输入维保电话"
                      clearable></el-input></el-form-item>
                  <el-form-item label="维保联系人">
                    <el-input v-model="ruleForm.maintenancePerson"
                      placeholder="请输入维保联系人"
                      clearable></el-input></el-form-item>
                  <el-form-item label="ip地址">
                    <el-input v-model="ruleForm.ipAddr"
                      placeholder="请输入ip地址"
                      clearable></el-input></el-form-item>
                </div>
              </el-form>
            </el-card>
          </el-main>
          <el-footer>
            <el-button @click="cancel('ruleForm')"
              style="margin-right: 10px">取 消</el-button>
            <el-button type="primary"
              @click="
                title == '新增网关'
                  ? submitAdd('ruleForm')
                  : submitEdit('ruleForm')
              ">
              确定
            </el-button>
          </el-footer>
        </el-container>
      </div>
      <div v-else>
        <el-container>
          <el-main>
            <el-card class="card"
              shadow="never"
              style="border: 0">
              <el-descriptions border
                :column="1"
                :labelStyle="{ width: '120px' }">
                <el-descriptions-item>
                  <template slot="label"> 所属部门: </template>
                  {{ serverDetail.deptName }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> 所属网格: </template>
                  {{ serverDetail.gridMountFullPathText }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> 网关名称: </template>
                  {{ serverDetail.serverName }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> 网关型号: </template>
                  {{ serverDetail.serverModel }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> 所在位置: </template>
                  {{ serverDetail.serverLocation }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> 维保单位: </template>
                  {{ serverDetail.maintenanceUnit }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> 维保电话: </template>
                  {{ serverDetail.maintenancePhone }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> 维保联系人: </template>
                  {{ serverDetail.maintenancePerson }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> ip地址: </template>
                  {{ serverDetail.ipAddr }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> 创建时间: </template>
                  {{ serverDetail.createdTime }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template slot="label"> 更新时间: </template>
                  {{ serverDetail.updatedTime }}
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-main>
          <el-footer>
            <el-button @click="showDialog = false">关闭</el-button>
          </el-footer>
        </el-container>
      </div>
    </el-dialog>
  </div>
  <!-- 对话框(添加、编辑) -->
</template>

<script>
import fireFightManageApi from '@/api/firefight-manage'
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import dataTableMixins from '@/mixins/data-table-mixins'
import { validIPAddr } from '@/utils/my-validate'
import Pagination from '@/components/Pagination'
export default {
  components: {
    Treeselect,
    Pagination
  },
  mixins: [dataTableMixins],
  data () {
    return {
      title: '', // 标题
      showDialog: false, // 显示对话框
      isDetail: false, //是否详情
      // 搜索表单
      form: {
        serverName: '',
        serverModel: '',
        createdTime: '',
      },

      serverDetail: {}, //网关详情

      selectedList: [], //选中列表数据
      // 添加列表
      ruleForm: {
        id: null,
        serverName: null,
        serverModel: null,
        serverLocation: null,
        maintenanceUnit: null,
        maintenancePhone: null,
        maintenancePerson: null,
        ipAddr: null,
        gridMount: null, // 所属网格id
        gridMountName: null,
        gridMountFullPath: null,
        gridMountFullPathText: null,
        deptGuid: null, // 所属部门id
        deptName: null,
      },
      // 表单验证
      rules: {
        gridMount: [
          { required: true, message: '请选择所属网格', trigger: 'change' },
        ],
        deptGuid: [
          { required: true, message: '请选择所属部门', trigger: 'change' },
        ],
        serverName: [
          { required: true, message: '请输入网关名称', trigger: 'blur' },
        ],
        serverModel: [
          { required: true, message: '请输入网关型号', trigger: 'blur' },
        ],
        serverLocation: [
          { required: true, message: '请输入所在位置', trigger: 'blur' },
        ],
      },
      gridTree: [], //网格树形列表
      deptTree: [], //部门树形列表
    }
  },
  watch: {},
  created () { },
  mounted () {
    this.getDataList()
    this.getGrid()
    this.getDept()
  },
  methods: {
    // 获取列表分页数据
    getDataList () {
      let createdTimeFrom = '',
        createdTimeTo = ''
      if (Array.isArray(this.form.createdTime)) {
        createdTimeFrom = this.form.createdTime[0]
        createdTimeTo = this.form.createdTime[1]
      }

      fireFightManageApi
        .getServerList({
          ...this.pagination,
          serverName: this.form.serverName,
          serverModel: this.form.serverModel,
          createdTimeFrom: createdTimeFrom,
          createdTimeTo: createdTimeTo,
        })
        .then((res) => {
          if (res.status === 200) {
            this.dataList = res.data.data.rows
            this.total = res.data.data.total
          } else {
            this.$message.error('获取网关列表失败,请重试!')
          }
        })
    },
    // 获取网格列表
    getGrid () {
      fireFightManageApi.getGridTree().then((res) => {
        if (res.status === 200) {
          // console.log(res.data.data.rows, '网格列表')
          this.gridTree = res.data.data.rows
        }
      })
    },
    // 获取部门列表
    getDept () {
      fireFightManageApi.getDeptTree().then((res) => {
        if (res.status === 200) {
          this.deptTree = res.data.data.rows
        }
      })
    },
    // 多选
    handleSelectionChange (val) {
      // console.log(val, '选中')
      this.selectedList = val // 存储选中数据
    },
    // 搜索
    search () {
      this.pagination.pageNum = 1
      this.getDataList()
    },

    // 重置
    reset () {

      Object.keys(this.form).forEach((key) => {
        this.form[key] = null
      })
      this.clearRuleForm()
      this.search()
    },
    // 取消
    cancel (formName) {
      this.clearRuleForm()
      this.$nextTick(() => {
        this.$refs[formName].clearValidate() //清空校验
      })
      this.showDialog = false
    },
    // 关闭按钮
    clickCloseBtn (done) {
      this.clearRuleForm()
      done()
    },
    // 新增
    add () {
      this.title = '新增网关'
      this.showDialog = true
      this.isDetail = false
      console.log(this.ruleForm, '新增')
    },
    // 提交新增
    submitAdd (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.ipAddr && this.ruleForm.ipAddr != '') {
            if (!validIPAddr(this.ruleForm.ipAddr)) {
              this.$message({
                message: 'ip地址输入的值不正确，请重新输入',
                type: 'warning',
                duration: 4000,
              })
              return
            }
          }

          fireFightManageApi.addServer(this.ruleForm).then((res) => {
            if (res.status === 200) {
              this.$message({
                message: '添加成功!',
                type: 'success',
              })
              this.$refs[formName].clearValidate()
              this.reset()
              this.showDialog = false
            } else {
              this.$message.error('添加失败,请重试!')
            }
          })
        } else {
          return false
        }
      })
    },
    // 删除
    handleDelete (val) {
      this.$confirm('是否删除该网关?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(
        () => {
          fireFightManageApi
            .deleteServer({
              id: val.id,
            })
            .then((res) => {
              if (res.status === 200) {
                this.$message({
                  message: '删除成功!',
                  type: 'success',
                })
                this.reset()
                this.showDialog = false
              } else {
                this.$message.error('删除失败,请重试!')
              }
            })
        },
        () => { }
      )
    },
    // 多数据删除
    multiDelete () {
      let ids = []
      if (this.selectedList.length == 0) {
        this.$message({
          message: '请选择要删除的网关',
          type: 'warning',
        })
      } else {
        this.selectedList.forEach((e) => {
          ids.push(e.id)
        })

        this.$confirm('是否删除选中数据?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(
          () => {
            fireFightManageApi.deleteMultiServer(ids.join(',')).then((res) => {
              if (res.status == 200) {
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                })
                this.reset()
              } else {
                this.$message.error('删除失败,请重试!')
              }
            })
          },
          () => { }
        )
      }
    },
    // 详情
    detail (val) {
      fireFightManageApi.getServerDetail(val.id).then((res) => {
        if (res.status === 200) {
          this.serverDetail = res.data
          this.title = '网关详情'
          this.showDialog = true
          this.isDetail = true
        } else {
          this.$message.error('打开详情失败')
        }
      })
    },
    // 编辑
    edit (val) {
      // console.log(val, '编辑')
      this.isDetail = false
      this.showDialog = true
      this.title = '编辑网关'
      Object.keys(this.ruleForm).forEach((key) => {
        Object.keys(val).forEach((_key) => {
          if (key == _key) {
            this.ruleForm[key] = val[_key]
          }
        })
      })
      console.log('ruleForm=', this.ruleForm)
    },
    // 提交编辑
    submitEdit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.ipAddr && this.ruleForm.ipAddr != '') {
            if (!validIPAddr(this.ruleForm.ipAddr)) {
              this.$message({
                message: 'ip地址输入的值不正确，请重新输入',
                type: 'warning',
                duration: 4000,
              })
              return
            }
          }
          console.log('ruleForm=', this.ruleForm)
          fireFightManageApi.updateServer(this.ruleForm).then((res) => {
            if (res.status === 200) {
              this.$message({
                message: '编辑成功!',
                type: 'success',
              })
              this.$refs[formName].clearValidate()
              this.showDialog = false
              this.reset()
            } else {
              this.$message.error('编辑失败,请重试!')
            }
          })
        }
      })
    },
    // 自定义树形控件键名
    normalizer (node) {
      return {
        id: node.guid,
        label: node.label,
        children: node.children,
      }
    },
    // 获取部门节点数据
    getDeptNode (node) {
      this.ruleForm.deptName = node.label
    },
    // 获取网格节点数据
    getGridNode (node) {
      console.log(node)
      this.ruleForm.gridMountName = node.label
      this.ruleForm.gridMountFullPathText = node.fullPathText
    },
    //重置ruleForm
    clearRuleForm () {
      Object.keys(this.ruleForm).forEach((e) => {
        this.ruleForm[e] = null
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import '../../../../../styles/part-custom';
</style>
